package com.dcbeida.utils;

import android.util.Log;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.dcbeida.bean.ResultModel;

/**
 * Created by hp on 2016/7/7.
 */
public class GetApi {


    public static final String KEY = "beida#$%543";
    public static final String APPID = "100001";

    public static TreeMap<String, String> keyParams;


    /**
     * 把服务器需要的固定参数整合
     *
     * @author sean
     */
    private static Map<String, String> doParams() {

        Map<String, String> mParams = new HashMap<String, String>();
//        mParams.put("KEY", KEY);
        mParams.put("timespan", System.currentTimeMillis() + "");
        return mParams;

    }

    /**
     * 根据输入参数生成签名，然后组合成访问服务器的地址
     *
     * @param mParams 存储所有入参数据
     * @param keyName 去掉某个入参关键字，不让其加入条件（输入#表示全部加入）
     * @return StringBuffer
     * @author sean
     */
    private static StringBuilder doUrl(
            Map<String, String> mParams, String keyName) {

        List<String> keyList = new ArrayList<>();
        StringBuffer strbuf = new StringBuffer();
        StringBuilder builder = new StringBuilder();
        try {

            Iterator<String> it = mParams.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                keyList.add(key);
            }


            //升序
            Collections.sort(keyList, new Comparator<String>() {
                @Override
                public int compare(String str1, String str2) {
                    if (str1.compareTo(str2) > 0) {
                        return 1;
                    }
                    if (str1.compareTo(str2) < 0) {
                        return -1;
                    }
                    return 0;
                }
            });

            //主装hash
            for (String key : keyList) {
                strbuf.append(mParams.get(key));
            }

            strbuf.append(KEY);

            Log.i("info", "strbuf=" + strbuf.toString());
            String hash = MD5Util.MD5(strbuf.toString()).toLowerCase();


            mParams.put("hash", hash);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("error", e.getMessage() + "");
        }

        Iterator<String> it2 = mParams.keySet().iterator();
        while (it2.hasNext()) {
            String key = it2.next();
            builder.append(key);
            builder.append("=");
            builder.append(mParams.get(key));
            builder.append("&");
        }

        builder.deleteCharAt(builder.length() - 1);
        return builder;
    }


    /**
     * 查询
     *
     * @param code 二维码
     * @return
     */
    public static ResultModel getdruginfo(String code) {
        ResultModel ret = null;
        try {

            String service = "getdruginfo";
            Map<String, String> mParams = doParams();
            mParams.put("service", service);
            mParams.put("code", code);
            StringBuilder jsonBuf = doUrl(mParams, "");
            String jsonstr = GenApiHashUrl.getInstance().Http_Post(jsonBuf.toString());


            if (jsonstr != null && !"".equals(jsonstr)) {
                try {
                    JSONObject resObject = new JSONObject(jsonstr);
                    ret = JSONFunctions.doJson(resObject);
                } catch (Exception e) {
                    Log.e("fancl", "DoJSONObj.error::::" + e.toString());
                    ret = new ResultModel();
                    ret.setErrcode(999);
                    return ret;
                }
            } else {
                ret = new ResultModel();
                ret.setErrcode(999);
                ret.setErrmsg("服务器请求失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            ret = new ResultModel();
            ret.setErrcode(999);
            return ret;
        }

        return ret;
    }
}
